package com.example.config;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.lettuce.core.ClientOptions;
import io.lettuce.core.TimeoutOptions;
import io.lettuce.core.cluster.ClusterClientOptions;
import io.lettuce.core.cluster.ClusterTopologyRefreshOptions;
import io.lettuce.core.protocol.ProtocolVersion;
import io.lettuce.core.resource.ClientResources;
import io.lettuce.core.resource.DefaultClientResources;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.AutoConfigureAfter;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.cache.CacheManager;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.cache.RedisCacheConfiguration;
import org.springframework.data.redis.cache.RedisCacheManager;
import org.springframework.data.redis.connection.*;
import org.springframework.data.redis.connection.lettuce.LettuceClientConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.connection.lettuce.LettucePoolingClientConfiguration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.RedisSerializationContext;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.util.ObjectUtils;

import java.time.Duration;
import java.util.HashSet;

/**
 * @author: Atosw
 * @date: 2024/11/10
 * @version: 1.0
 * @description:
 */
@Slf4j
@EnableCaching
@Configuration
@AutoConfigureAfter(RedisAutoConfiguration.class)
public class RedisConfig {
    /**
     * 模式：single单机/cluster集群/sentinel哨兵
     */
    @Value("${spring.redis.type:single}")
    private String type;
    /**
     * RESP2/RESP3协议；redis6.0后的新协议，大大提高了应用程序的响应速度，并降低了数据库的压力
     */
    @Value("${spring.redis.lettuce.client.protocolVersion:RESP3}")
    private String protocolVersion;
    /**
     * 拓扑图刷新时间(秒, 默认30秒)
     */
    @Value("${spring.redis.topology.refresh-time:30}")
    private Integer topologyRefreshTime;

    /**
     * 配置自定义redisTemplate
     *
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean
    public RedisTemplate<String, Object> redisTemplate(@Qualifier("lettuceConnectionFactory") RedisConnectionFactory lettuceConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(lettuceConnectionFactory);
        // 使用StringRedisSerializer来序列化和反序列化redis的key值
        template.setKeySerializer(new StringRedisSerializer());
        // 使用json来序列化value
        template.setValueSerializer(jackson2JsonRedisSerializer());
        // 设置hash key 和value序列化模式
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(jackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }

    /**
     * 配置json序列化
     *
     * @return
     */
    @Bean
    public RedisSerializer<Object> jackson2JsonRedisSerializer() {
        // 使用Jackson2JsonRedisSerializer来序列化和反序列化redis的value值
        Jackson2JsonRedisSerializer serializer = new Jackson2JsonRedisSerializer(Object.class);
        ObjectMapper mapper = new ObjectMapper();
        // 指定要序列化的域，field,get和set,以及修饰符范围，ANY是都有包括private和public
        mapper.setVisibility(PropertyAccessor.ALL, JsonAutoDetect.Visibility.ANY);
        // 指定序列化输入的类型，类必须是非final修饰的，final修饰的类，比如String,Integer等会跑出异常
        mapper.enableDefaultTyping(ObjectMapper.DefaultTyping.NON_FINAL);
        serializer.setObjectMapper(mapper);
        return serializer;
    }

    /**
     * 配置缓存管理器；此处的配置可以作用于业务类，和@Cacheable @CachePut @CacheEvict配合使用，实现业务结果的缓存操作
     *
     * @param lettuceConnectionFactory
     * @return
     */
    @Bean
    public CacheManager cacheManager(@Qualifier("lettuceConnectionFactory") RedisConnectionFactory lettuceConnectionFactory) {
        // 生成一个默认配置，通过config对象即可对缓存进行自定义配置
        RedisCacheConfiguration config = RedisCacheConfiguration.defaultCacheConfig();
        // 设置缓存的默认过期时间，也是使用Duration设置
        config.entryTtl(Duration.ofDays(1))
                // 设置 key为string序列化
                .serializeKeysWith(RedisSerializationContext.SerializationPair.fromSerializer(new StringRedisSerializer()))
                // 设置value为json序列化
                .serializeValuesWith(RedisSerializationContext.SerializationPair.fromSerializer(jackson2JsonRedisSerializer()))
                // 不缓存空值
                .disableCachingNullValues();
        // 使用自定义的缓存配置初始化一个cacheManager
        return RedisCacheManager.builder(lettuceConnectionFactory)
                // 一定要先调用该方法设置初始化的缓存名，再初始化相关的配置
                .build();
    }

    /**
     * 配置默认客户端资源
     *
     * @return
     */
    @Bean
    public DefaultClientResources lettuceClientResources() {
        return DefaultClientResources.create();
    }

    /**
     * 配置redis连接工厂
     *
     * @param redisProperties
     * @param clientResources
     * @return
     * @throws Exception
     */
    @Bean
    public LettuceConnectionFactory lettuceConnectionFactory(RedisProperties redisProperties, ClientResources clientResources) throws Exception {
        switch (type) {
            case "single":
                log.info("Redis is StandaloneMode [" + redisProperties.getHost() + ":" + redisProperties.getPort() + "]");
                RedisStandaloneConfiguration redisConfig = new RedisStandaloneConfiguration(redisProperties.getHost(), redisProperties.getPort());
                redisConfig.setDatabase(redisProperties.getDatabase());
                redisConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));
                return new LettuceConnectionFactory(redisConfig, LettuceClientConfiguration.builder()
                        .clientResources(clientResources)
                        .clientOptions(ClientOptions.builder()
                                .timeoutOptions(TimeoutOptions.enabled(getRedisTimeout(redisProperties)))
                                .protocolVersion(getPv())
                                .build())
                        .build());
            case "cluster":
                log.info("Redis is ClusterMode " + redisProperties.getCluster().getNodes());
                RedisClusterConfiguration clusterConfig = new RedisClusterConfiguration(redisProperties.getCluster().getNodes());
                clusterConfig.setMaxRedirects(getMaxRedirects(redisProperties));
                clusterConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));
                return new LettuceConnectionFactory(clusterConfig, LettuceClientConfiguration.builder()
                        .clientResources(clientResources)
                        .clientOptions(ClusterClientOptions.builder()
                                .timeoutOptions(TimeoutOptions.enabled(getRedisTimeout(redisProperties)))
                                .topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
                                        .enablePeriodicRefresh(getTopologyRefreshTime()) //按照周期刷新拓扑
                                        .enableAllAdaptiveRefreshTriggers() //根据事件刷新拓扑
                                        .build())
                                .protocolVersion(getPv())
                                .build())
                        .build());
            case "sentinel":
                log.info("Redis is SentinelMode " + redisProperties.getSentinel().getNodes());
                RedisSentinelConfiguration sentinelConfig = new RedisSentinelConfiguration(redisProperties.getSentinel().getMaster(), new HashSet<>(redisProperties.getSentinel().getNodes()));
                sentinelConfig.setDatabase(redisProperties.getDatabase());
                sentinelConfig.setPassword(RedisPassword.of(redisProperties.getPassword()));
                return new LettuceConnectionFactory(sentinelConfig, LettuceClientConfiguration.builder()
                        .clientResources(clientResources)
                        .clientOptions(ClusterClientOptions.builder()
                                .timeoutOptions(TimeoutOptions.enabled(getRedisTimeout(redisProperties)))
                                .topologyRefreshOptions(ClusterTopologyRefreshOptions.builder()
                                        .enablePeriodicRefresh(getTopologyRefreshTime()) //按照周期刷新拓扑
                                        .enableAllAdaptiveRefreshTriggers() //根据事件刷新拓扑
                                        .build())
                                .protocolVersion(getPv())
                                .build())
                        .build());
            default:
                throw new Exception("不支持的Redis部署模式");
        }
    }

    /**
     * 获取协议
     *
     * @return
     */
    private ProtocolVersion getPv() {
        switch (protocolVersion) {
            case "RESP3":
                return ProtocolVersion.RESP3;
            case "RESP2":
            default:
                return ProtocolVersion.RESP2;
        }
    }

    /**
     * 最大重定向次数
     *
     * @param redisProperties
     * @return
     */
    private int getMaxRedirects(RedisProperties redisProperties) {
        Integer maxRedirects = redisProperties.getCluster().getMaxRedirects();
        return null == maxRedirects ? 5 : maxRedirects;
    }

    /**
     * 获取刷新周期
     *
     * @return
     */
    private Duration getTopologyRefreshTime() {
        return Duration.ofSeconds(null == topologyRefreshTime ? 30 : topologyRefreshTime);
    }

    /**
     * 获取超时时间
     *
     * @param redisProperties
     * @return
     */
    private Duration getRedisTimeout(RedisProperties redisProperties) {
        Duration timeout = redisProperties.getTimeout();
        return null == timeout ? Duration.ofSeconds(10) : timeout;
    }
}
